<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 19-4-2
 * Time: 下午5:27
 */

namespace common\components\huaxiayinhang;


use common\components\tools\Model;
use common\components\tools\Tools;
use common\models\NbrbAdditionalRecordApply;
use common\models\NbrbAttachmentUpload;
use common\models\NbrbCustomAdmittance;
use common\models\NbrbFinalAuditApply;
use common\models\NbrbLoanApply;
use common\models\NbrbPledgeInfoNotice;
use common\models\NbrbRequestLog;
use common\models\NbrbUnderwriteApply;
use wodrow\yii\rest\ApiException;
use GuzzleHttp\Client;
use yii\base\Component;
use yii\db\Exception;

/**
 * 宁波人保
 * Class Nbrb
 * @package common\components\huaxiayinhang
 */
class Nbrb extends Component
{
    /**
     * @var NbrbRequestLog $req_log
     */
    public $req_log;

    public function init()
    {
        parent::init();
        $this->req_log = new NbrbRequestLog();
        $this->req_log->request_action = \Yii::$app->controller->route;
        $this->req_log->created_at = time();
        $this->req_log->request_data = json_encode($_REQUEST, JSON_UNESCAPED_UNICODE);
        $this->req_log->generateRequestSeqNo();
        $this->req_log->request_item_code = Config::$xmbm;
        $this->req_log->request_company_code = Config::$zgsbm;
    }

    /**
     * 14.附件上传
     * @param $orderNumber
     * @param $attachmentType
     * @param $file_url
     * @param $number
     * @return array
     * @throws
     */
    public function attachmentUpload($orderNumber, $attachmentType, $file_url, $number)
    {
        $this->req_log->request_order_num = $orderNumber;
        $this->req_log->request_attachment_type = $attachmentType;
        $this->req_log->request_file_url = $file_url;
        $this->req_log->request_number = $number;
        $r = [];
        if ($orderNumber){
            $att = NbrbAttachmentUpload::findOne(['file_url' => $file_url, 'attachment_type' => $attachmentType, 'number' => $number, 'order_number' => $orderNumber]);
        }else{
            $att = NbrbAttachmentUpload::findOne(['file_url' => $file_url, 'attachment_type' => $attachmentType, 'number' => $number]);
        }
        if (!$att){
            $att = new NbrbAttachmentUpload();
            $att->file_url = $file_url;
            $att->attachment_type = $attachmentType;
            $client = new Client([
                'base_uri' => Config::$fjsclddz,
            ]);
            $resp = $client->post('', [
                'headers' => [
                    'Content-Type => multipart/form-data',
                ],
                'multipart' => [
                    [
                        'name' => 'file',
                        'contents' => fopen($file_url, 'r'),
                    ],
                    [
                        'name' => 'requestSeqNo',
                        'contents' => $this->req_log->request_seq_no,
                    ],
                    [
                        'name' => 'itemCode',
                        'contents' => $this->req_log->request_item_code,
                    ],
                    [
                        'name' => 'companyCode',
                        'contents' => $this->req_log->request_company_code,
                    ],
                    [
                        'name' => 'orderNumber',
                        'contents' => $orderNumber,
                    ],
                    [
                        'name' => 'attachmentType',
                        'contents' => $attachmentType,
                    ],
                    [
                        'name' => 'number',
                        'contents' => $number,
                    ],
                ],
            ]);
            $resp_contents = $resp->getBody()->getContents();
            $plat_resp = json_decode($resp_contents, true);
            $this->req_log->resp_data = $resp_contents;
            $att->request_seq_no = $this->req_log->request_seq_no;
            $att->order_number = $orderNumber;
            $att->number = $number;
            $att->created_at = time();
            if (isset($plat_resp['success']) && $plat_resp['success'] == 'Y'){
                $r['_info'] = $plat_resp;
                $this->req_log->resp_success = $plat_resp['success'];
                $this->req_log->resp_at_number = $plat_resp['atNumber'];
            }else{
                throw new ApiException(201904041011, "上传附件失败：".$resp_contents);
            }
            if (!$this->req_log->save()){
                throw new Exception(Model::getModelError($this->req_log));
            }
            $att->at_number = $this->req_log->resp_at_number;
            $r['log'] = $this->req_log->toArray();
        }
        $att->updated_at = time();
        if (!$att->save()){
            throw new Exception(Model::getModelError($att));
        }
        $r['model'] = $att->toArray();
        return $r;
    }

    public function encryptAndSign(&$mapData, $map, $now)
    {
        $mapData['requestSeqNo'] = $this->req_log->request_seq_no;//请求流水号
        $mapData['itemCode'] = $this->req_log->request_item_code;//项目编号
        $mapData['companyCode'] = $this->req_log->request_company_code;//子公司编号
        $mapData['interfaceCode']= $this->req_log->request_interface_code;//接口编号
        $mapData['interfaceVersion'] = $this->req_log->request_interface_version;//接口版本号
        $mapData['infoContent'] = $this->encryptBody($map, $now);//加密报文内容
        $mapData['infoSign'] = $this->sign($mapData);//报文签名
        $mapData = json_encode($mapData, JSON_UNESCAPED_UNICODE);
        $this->req_log->nbrb_req_data = $mapData;
        $mapData = urlencode($mapData);
    }

    /**
     * 1.客户准入
     * @param $json
     * @param $force
     * @return array
     * @throws
     */
    public function customAdmittance($json, $force)
    {
        $this->req_log->request_json = $json;
        $this->req_log->request_interface_code = "AccessApply";
        $this->req_log->request_interface_version = "v1";
        $data = $json;
        $map = json_decode($data, true);
        $model = NbrbCustomAdmittance::findOne(['req_name' => $map['name'], 'req_cert_type' => $map['certType'], 'req_cert_no' => $map['certNo'], 'req_phone' => $map['phone']]);
        if ($force || !$model){
            if ($model){
                $model->delete();
            }
            $model = new NbrbCustomAdmittance();
            $model->req_name = $map['name'];
            $model->req_cert_type = $map['certType'];
            $model->req_cert_no = $map['certNo'];
            $model->req_phone = $map['phone'];
            $now = time();
            $mapData = [];
            $this->encryptAndSign($mapData, $map, $now);
            $client = new Client([
                'base_uri' => Config::$jklddz,
            ]);
            $resp = $client->post('', [
                'headers' => [
                    'Accept' => 'application/json',
                ],
                'body' => $mapData,
            ]);
            $resp_contents = urldecode($resp->getBody()->getContents());
            $this->req_log->resp_data = $resp_contents;
            $plat_resp = json_decode($resp_contents, true);
            $r = [
                'plat_resp' => $plat_resp,
            ];
            if (isset($plat_resp['respCode']) && $plat_resp['respCode'] == 'S'){
                $_info = $this->decryptInfoContent($plat_resp['infoContent']);
                $r['_info'] = json_decode($_info, true);
                $this->req_log->resp_code = $plat_resp['respCode'];
                $this->req_log->resp_info = $_info;
                $this->req_log->resp_info_code = $r['_info']['code'];
                if (in_array($this->req_log->resp_info_code, ['00'])){
                    $this->req_log->resp_info_order_number = $r['_info']['orderNumber'];
                    $this->req_log->resp_info_access_number = $r['_info']['accessNumber'];
                    $model->request_seq_no = $this->req_log->request_seq_no;
                    $model->request_json = $this->req_log->request_json;
                    $model->created_at = $now;
                    $model->status = NbrbCustomAdmittance::STATUS_ACTIVE;
                    $model->order_number = $this->req_log->resp_info_order_number;
                    $model->access_number = $this->req_log->resp_info_access_number;
                    if (!$model->save()){
                        throw new Exception(Model::getModelError($model));
                    }
                }else{
                    throw new ApiException(201904041719, "准入失败:".$_info);
                }
                if (!$this->req_log->save()){
                    throw new Exception(Model::getModelError($this->req_log));
                }
                $r['log'] = $this->req_log->toArray();
            }else{
                throw new ApiException(201904041157, "准入失败:".$resp_contents);
            }
        }
        $model->request_json = json_decode($model->request_json, true);
        $r['model'] = $model->toArray();
        return $r;
    }

    /**
     * 3.核保申请
     * @param $json
     * @param $force
     * @return mixed
     * @throws ApiException
     * @throws
     */
    public function underwriteApply($json, $force)
    {
        $this->req_log->request_json = $json;
        $this->req_log->request_interface_code = "UnderWriteApply";
        $this->req_log->request_interface_version = "v1";
        $data = $json;
        $map = json_decode($data, true);
        $this->req_log->request_order_num = $order_number = $map['orderNumber'];
        $ca = NbrbCustomAdmittance::findOne(['order_number' => $order_number]);
        if (!$ca){
            throw new ApiException(201904041534, "没有找到准入单子");
        }
        if (!in_array($ca->nbrbRequestLog->resp_info_code, ['00'])){
            throw new ApiException(201904041607, "准入未通过");
        }
        $model = $ca->nbrbUnderwriteApply;
        if ($force || !$model){
            if ($model){
                $model->delete();
            }
            $model = new NbrbUnderwriteApply();
            $model->req_order_number = $ca->order_number;
            $now = time();
            $mapData = [];
            $this->encryptAndSign($mapData, $map, $now);
            $client = new Client([
                'base_uri' => Config::$jklddz,
            ]);
            $resp = $client->post('', [
                'headers' => [
                    'Accept' => 'application/json',
                ],
                'body' => $mapData,
            ]);
            $resp_contents = urldecode($resp->getBody()->getContents());
            $this->req_log->resp_data = $resp_contents;
            $plat_resp = json_decode($resp_contents, true);
            $r = [
                'plat_resp' => $plat_resp,
            ];
            if (isset($plat_resp['respCode']) && $plat_resp['respCode'] == 'S'){
                $_info = $this->decryptInfoContent($plat_resp['infoContent']);
                $r['_info'] = json_decode($_info, true);
                $this->req_log->resp_code = $plat_resp['respCode'];
                $this->req_log->resp_info = $_info;
                $this->req_log->resp_info_code = $r['_info']['code'];
                if (in_array($this->req_log->resp_info_code, ['00', '03'])){
                    $this->req_log->resp_info_order_number = $r['_info']['orderNumber'];
                    if ($this->req_log->resp_info_order_number != $model->req_order_number){
                        throw new ApiException(201904041743, "回调订单号不一致");
                    }
                    $model->request_seq_no = $this->req_log->request_seq_no;
                    $model->request_json = $this->req_log->request_json;
                    $model->created_at = $now;
                    $model->status = NbrbCustomAdmittance::STATUS_ACTIVE;
                    $this->req_log->resp_info_underwrite_number = $r['_info']['underWriteNumber'];
                    $model->underwrite_number = $this->req_log->resp_info_underwrite_number;
                    if (!$model->save()){
                        throw new Exception(Model::getModelError($model));
                    }
                }else{
                    throw new ApiException(201904041723, "核保失败:".$_info);
                }
                if (!$this->req_log->save()){
                    throw new Exception(Model::getModelError($this->req_log));
                }
                $r['log'] = $this->req_log->toArray();
            }else{
                throw new ApiException(201904041707, "核保失败:".$resp_contents);
            }
        }
        $model->request_json = json_decode($model->request_json, true);
        $r['model'] = $model->toArray();
        return $r;
    }

    /**
     * 5.车辆信息补录
     * @param $json
     * @param $force
     * @return mixed
     * @throws ApiException
     * @throws
     */
    public function additionalRecordApply($json, $force)
    {
        $this->req_log->request_json = $json;
        $this->req_log->request_interface_code = "AdditionalRecordApply";
        $this->req_log->request_interface_version = "v1";
        $data = $json;
        $map = json_decode($data, true);
        $this->req_log->request_order_num = $order_number = $map['orderNumber'];
        $ca = NbrbCustomAdmittance::findOne(['order_number' => $order_number]);
        if (!$ca){
            throw new ApiException(201904091406, "没有找到准入单子");
        }
        if (!in_array($ca->nbrbRequestLog->resp_info_code, ['00'])){
            throw new ApiException(201904091407, "准入未通过");
        }
        $model = NbrbAdditionalRecordApply::findOne(['req_order_number' => $order_number]);
        if ($force || !$model) {
            if ($model){
                $model->delete();
            }
            $model = new NbrbAdditionalRecordApply();
            $model->req_order_number = $ca->order_number;
            $now = time();
            $mapData = [];
            $this->encryptAndSign($mapData, $map, $now);
            $client = new Client([
                'base_uri' => Config::$jklddz,
            ]);
            $resp = $client->post('', [
                'headers' => [
                    'Accept' => 'application/json',
                ],
                'body' => $mapData,
            ]);
            $resp_contents = urldecode($resp->getBody()->getContents());
            $this->req_log->resp_data = $resp_contents;
            $plat_resp = json_decode($resp_contents, true);
            $r = [
                'plat_resp' => $plat_resp,
            ];
            if (isset($plat_resp['respCode']) && $plat_resp['respCode'] == 'S'){
                $_info = $this->decryptInfoContent($plat_resp['infoContent']);
                $r['_info'] = json_decode($_info, true);
                $this->req_log->resp_code = $plat_resp['respCode'];
                $this->req_log->resp_info = $_info;
                $this->req_log->resp_info_code = $r['_info']['code'];
                if (in_array($this->req_log->resp_info_code, ['00', '03'])){
                    $this->req_log->resp_info_order_number = $r['_info']['orderNumber'];
                    if ($this->req_log->resp_info_order_number != $model->req_order_number){
                        throw new ApiException(201904091708, "回调订单号不一致");
                    }
                    $model->request_seq_no = $this->req_log->request_seq_no;
                    $model->request_json = $this->req_log->request_json;
                    $model->created_at = $now;
                    $model->status = NbrbAdditionalRecordApply::STATUS_ACTIVE;
                    $this->req_log->resp_info_add_record_number = $r['_info']['addRecordNumber'];
                    $model->add_record_number = $this->req_log->resp_info_add_record_number;
                    if (!$model->save()){
                        throw new Exception(Model::getModelError($model));
                    }
                }else{
                    throw new ApiException(201904041723, "车辆信息补录失败:".$_info);
                }
                if (!$this->req_log->save()){
                    throw new Exception(Model::getModelError($this->req_log));
                }
                $r['log'] = $this->req_log->toArray();
            }
        }
        $model->request_json = json_decode($model->request_json, true);
        $r['model'] = $model->toArray();
        return $r;
    }

    /**
     * 7.终审请求
     * @param $json
     * @param $force
     * @return mixed
     * @throws ApiException
     * @throws
     */
    public function finalAduitApply($json, $force)
    {
        $this->req_log->request_json = $json;
        $this->req_log->request_interface_code = "FinalAduitApply";
        $this->req_log->request_interface_version = "v1";
        $data = $json;
        $map = json_decode($data, true);
        $this->req_log->request_order_num = $order_number = $map['orderNumber'];
        $ca = NbrbCustomAdmittance::findOne(['order_number' => $order_number]);
        if (!$ca){
            throw new ApiException(201904091537, "没有找到准入单子");
        }
        if (!in_array($ca->nbrbRequestLog->resp_info_code, ['00'])){
            throw new ApiException(201904091538, "准入未通过");
        }
        $model = NbrbFinalAuditApply::findOne(['req_order_number' => $order_number]);
        if ($force || !$model) {
            if ($model){
                $model->delete();
            }
            $model = new NbrbFinalAuditApply();
            $model->req_order_number = $ca->order_number;
            $now = time();
            $mapData = [];
            $this->encryptAndSign($mapData, $map, $now);
            $client = new Client([
                'base_uri' => Config::$jklddz,
            ]);
            $resp = $client->post('', [
                'headers' => [
                    'Accept' => 'application/json',
                ],
                'body' => $mapData,
            ]);
            $resp_contents = urldecode($resp->getBody()->getContents());
            $this->req_log->resp_data = $resp_contents;
            $plat_resp = json_decode($resp_contents, true);
            $r = [
                'plat_resp' => $plat_resp,
            ];
            if (isset($plat_resp['respCode']) && $plat_resp['respCode'] == 'S'){
                $_info = $this->decryptInfoContent($plat_resp['infoContent']);
                $r['_info'] = json_decode($_info, true);
                $this->req_log->resp_code = $plat_resp['respCode'];
                $this->req_log->resp_info = $_info;
                $this->req_log->resp_info_code = $r['_info']['code'];
                if (in_array($this->req_log->resp_info_code, ['00', '03'])){
                    $this->req_log->resp_info_order_number = $r['_info']['orderNumber'];
                    if ($this->req_log->resp_info_order_number != $model->req_order_number){
                        throw new ApiException(201904091510, "回调订单号不一致");
                    }
                    $model->request_seq_no = $this->req_log->request_seq_no;
                    $model->request_json = $this->req_log->request_json;
                    $model->created_at = $now;
                    $model->status = NbrbFinalAuditApply::STATUS_ACTIVE;
                    $this->req_log->resp_info_final_audit_number = $r['_info']['finalAduitNumber'];
                    $model->final_audit_number = $this->req_log->resp_info_final_audit_number;
                    if (!$model->save()){
                        throw new Exception(Model::getModelError($model));
                    }
                }else{
                    throw new ApiException(201904091511, "终审请求:".$_info);
                }
                if (!$this->req_log->save()){
                    throw new Exception(Model::getModelError($this->req_log));
                }
                $r['log'] = $this->req_log->toArray();
            }
        }
        $model->request_json = json_decode($model->request_json, true);
        $r['model'] = $model->toArray();
        return $r;
    }

    /**
     * 9.放款申请
     * @param $json
     * @param $force
     * @return mixed
     * @throws ApiException
     * @throws
     */
    public function loanApply($json, $force)
    {
        $this->req_log->request_json = $json;
        $this->req_log->request_interface_code = "LoanApply";
        $this->req_log->request_interface_version = "v1";
        $data = $json;
        $map = json_decode($data, true);
        $this->req_log->request_order_num = $order_number = $map['orderNumber'];
        $ca = NbrbCustomAdmittance::findOne(['order_number' => $order_number]);
        if (!$ca){
            throw new ApiException(201904091535, "没有找到准入单子");
        }
        if (!in_array($ca->nbrbRequestLog->resp_info_code, ['00'])){
            throw new ApiException(201904091536, "准入未通过");
        }
        $model = NbrbLoanApply::findOne(['req_order_number' => $order_number]);
        if ($force || !$model) {
            if ($model){
                $model->delete();
            }
            $model = new NbrbLoanApply();
            $model->req_order_number = $ca->order_number;
            $now = time();
            $mapData = [];
            $this->encryptAndSign($mapData, $map, $now);
            $client = new Client([
                'base_uri' => Config::$jklddz,
            ]);
            $resp = $client->post('', [
                'headers' => [
                    'Accept' => 'application/json',
                ],
                'body' => $mapData,
            ]);
            $resp_contents = urldecode($resp->getBody()->getContents());
            $this->req_log->resp_data = $resp_contents;
            $plat_resp = json_decode($resp_contents, true);
            $r = [
                'plat_resp' => $plat_resp,
            ];
            if (isset($plat_resp['respCode']) && $plat_resp['respCode'] == 'S'){
                $_info = $this->decryptInfoContent($plat_resp['infoContent']);
                $r['_info'] = json_decode($_info, true);
                $this->req_log->resp_code = $plat_resp['respCode'];
                $this->req_log->resp_info = $_info;
                $this->req_log->resp_info_code = $r['_info']['code'];
                if (in_array($this->req_log->resp_info_code, ['00', '03'])){
                    $this->req_log->resp_info_order_number = $r['_info']['orderNumber'];
                    if ($this->req_log->resp_info_order_number != $model->req_order_number){
                        throw new ApiException(201904091708, "回调订单号不一致");
                    }
                    $model->request_seq_no = $this->req_log->request_seq_no;
                    $model->request_json = $this->req_log->request_json;
                    $model->created_at = $now;
                    $model->status = NbrbLoanApply::STATUS_ACTIVE;
                    $this->req_log->resp_info_loan_apply_number = $r['_info']['loanApplyNumber'];
                    $model->loan_apply_number = $this->req_log->resp_info_loan_apply_number;
                    if (!$model->save()){
                        throw new Exception(Model::getModelError($model));
                    }
                }else{
                    throw new ApiException(201904091514, "放款申请:".$_info);
                }
                if (!$this->req_log->save()){
                    throw new Exception(Model::getModelError($this->req_log));
                }
                $r['log'] = $this->req_log->toArray();
            }
        }
        $model->request_json = json_decode($model->request_json, true);
        $r['model'] = $model->toArray();
        return $r;
    }

    /**
     * 11.保单信息获取
     * @param $json
     * @param $force
     * @return mixed
     * @throws ApiException
     * @throws
     */
    public function getPolicyDetail($json, $force)
    {
        $this->req_log->request_json = $json;
        $this->req_log->request_interface_code = "GetPolicyDetail";
        $this->req_log->request_interface_version = "v1";
        $data = $json;
        $map = json_decode($data, true);
        $now = time();
        $mapData = [];
        $this->encryptAndSign($mapData, $map, $now);
        $client = new Client([
            'base_uri' => Config::$jklddz,
        ]);
        $resp = $client->post('', [
            'headers' => [
                'Accept' => 'application/json',
            ],
            'body' => $mapData,
        ]);
        $resp_contents = urldecode($resp->getBody()->getContents());
        $this->req_log->resp_data = $resp_contents;
        $plat_resp = json_decode($resp_contents, true);
        $r = [
            'plat_resp' => $plat_resp,
        ];
        if (isset($plat_resp['respCode']) && $plat_resp['respCode'] == 'S'){
            $_info = $this->decryptInfoContent($plat_resp['infoContent']);
            $r['_info'] = json_decode($_info, true);
        }
        return $r;
    }

    /**
     * 12.抵押信息推送
     * @param $json
     * @param $force
     * @return mixed
     * @throws ApiException
     * @throws
     */
    public function pledgeInfoNotice($json, $force)
    {
        $this->req_log->request_json = $json;
        $this->req_log->request_interface_code = "PledgeInfoNotice";
        $this->req_log->request_interface_version = "v1";
        $data = $json;
        $map = json_decode($data, true);
        $this->req_log->request_order_num = $order_number = $map['orderNumber'];
        $ca = NbrbCustomAdmittance::findOne(['order_number' => $order_number]);
        if (!$ca){
            throw new ApiException(201904111452, "没有找到准入单子");
        }
        if (!in_array($ca->nbrbRequestLog->resp_info_code, ['00'])){
            throw new ApiException(201904111453, "准入未通过");
        }
        $model = NbrbPledgeInfoNotice::findOne(['req_order_number' => $order_number]);
        if ($force || !$model) {
            if ($model){
                $model->delete();
            }
            $model = new NbrbPledgeInfoNotice();
            $model->req_order_number = $ca->order_number;
            $now = time();
            $mapData = [];
            $this->encryptAndSign($mapData, $map, $now);
            $client = new Client([
                'base_uri' => Config::$jklddz,
            ]);
            $resp = $client->post('', [
                'headers' => [
                    'Accept' => 'application/json',
                ],
                'body' => $mapData,
            ]);
            $resp_contents = urldecode($resp->getBody()->getContents());
            $this->req_log->resp_data = $resp_contents;
            $plat_resp = json_decode($resp_contents, true);
            $r = [
                'plat_resp' => $plat_resp,
            ];
            if (isset($plat_resp['respCode']) && $plat_resp['respCode'] == 'S'){
                $_info = $this->decryptInfoContent($plat_resp['infoContent']);
                $r['_info'] = json_decode($_info, true);
                $this->req_log->resp_code = $plat_resp['respCode'];
                $this->req_log->resp_info = $_info;
                $this->req_log->resp_info_code = $r['_info']['code'];
                if (in_array($this->req_log->resp_info_code, ['00', '03'])){
                    $this->req_log->resp_info_order_number = $r['_info']['orderNumber'];
                    if ($this->req_log->resp_info_order_number != $model->req_order_number){
                        throw new ApiException(201904101708, "回调订单号不一致");
                    }
                    $model->request_seq_no = $this->req_log->request_seq_no;
                    $model->request_json = $this->req_log->request_json;
                    $model->created_at = $now;
                    $model->status = NbrbPledgeInfoNotice::STATUS_ACTIVE;
                    $this->req_log->resp_info_pledge_info_number = $r['_info']['pledgeInfoNumber'];
                    $model->pledge_info_number = $this->req_log->resp_info_pledge_info_number;
                    if (!$model->save()){
                        throw new Exception(Model::getModelError($model));
                    }
                }else{
                    throw new ApiException(201904101723, "抵押信息推送失败:".$_info);
                }
                if (!$this->req_log->save()){
                    throw new Exception(Model::getModelError($this->req_log));
                }
                $r['log'] = $this->req_log->toArray();
            }
        }
        $model->request_json = json_decode($model->request_json, true);
        $r['model'] = $model->toArray();
        return $r;
    }

    /**
     * 15.贷后阶段-还款计划信息获取
     * @param $json
     * @param $force
     * @return mixed
     * @throws ApiException
     * @throws
     */
    public function getRepayPlanDetail($json, $force)
    {
        $this->req_log->request_json = $json;
        $this->req_log->request_interface_code = "GetRepayPlanDetail";
        $this->req_log->request_interface_version = "v1";
        $data = $json;
        $map = json_decode($data, true);
        $now = time();
        $mapData = [];
        $this->encryptAndSign($mapData, $map, $now);
        $client = new Client([
            'base_uri' => Config::$jklddz,
        ]);
        $resp = $client->post('', [
            'headers' => [
                'Accept' => 'application/json',
            ],
            'body' => $mapData,
        ]);
        $resp_contents = urldecode($resp->getBody()->getContents());
        $this->req_log->resp_data = $resp_contents;
        $plat_resp = json_decode($resp_contents, true);
        $r = [
            'plat_resp' => $plat_resp,
        ];
        if (isset($plat_resp['respCode']) && $plat_resp['respCode'] == 'S'){
            $_info = $this->decryptInfoContent($plat_resp['infoContent']);
            $r['_info'] = json_decode($_info, true);
        }
        return $r;
    }

    /**
     * @param $json
     * @param $force
     * @return mixed
     * @throws ApiException
     * @throws
     */
    public function getFile($json, $force)
    {
        $this->req_log->request_json = $json;
        $this->req_log->request_interface_code = "GetFile";
        $this->req_log->request_interface_version = "v1";
        $data = $json;
        $map = json_decode($data, true);
        $now = time();
        $mapData = [];
        $this->encryptAndSign($mapData, $map, $now);
        $client = new Client([
            'base_uri' => Config::$jklddz,
        ]);
        $resp = $client->post('', [
            'headers' => [
                'Accept' => 'application/json',
            ],
            'body' => $mapData,
        ]);
        $resp_contents = urldecode($resp->getBody()->getContents());
        $this->req_log->resp_data = $resp_contents;
        $plat_resp = json_decode($resp_contents, true);
        $r = [
            'plat_resp' => $plat_resp,
        ];
        if (isset($plat_resp['respCode']) && $plat_resp['respCode'] == 'S'){
            $_info = $this->decryptInfoContent($plat_resp['infoContent']);
            $r['_info'] = json_decode($_info, true);
        }
        return $r;
    }

    /**
     * @var array $certType 证件类型
     */
    public static $certType = [
        '01' => "身份证",
        '02' => "临时身份证",
        '03' => "港澳身份证",
    ];

    /**
     * @var array $bus 业务类型
     */
    public static $bus = [
        'BUS_001' => "按揭贷款",
        'BUS_002' => "存量",
        'BUS_003' => "融资租赁", // 废弃
        'BUS_004' => "融资租赁直租",
        'BUS_005' => "融资租赁回租",
    ];

    /**
     * @var array $cc 车辆构成
     */
    public static $cc = [
        'CC_001' => "新车",
        'CC_002' => "二手车",
        'CC_003' => "存量车",
    ];

    /**
     * @var array $carUsage 购车用途
     */
    public static $carUsage = [
        '01' => "个人自用",
        '02' => "单位自有",
        '03' => "载客营运",
        '04' => "载货营运",
        '05' => "出租营运",
        '06' => "其他",
    ];

    /**
     * @var array $repayType 还款方式
     */
    public static $repayType = [
        '01' => "等额本息",
        '02' => "等额本金",
    ];

    /**
     * @var array $repayRate 还款频率
     */
    public static $repayRate = [
        '01' => "月",
        '02' => "季",
        '03' => "年",
    ];

    /**
     * @var array $carColor 车辆颜色
     */
    public static $carColor = [
        '01' => "黑色",
        '02' => "白色",
        '03' => "红色",
        '04' => "黄色",
        '05' => "银色",
        '06' => "香槟色",
        '07' => "蓝色",
        '08' => "绿色",
        '99' => "其他",
    ];

    /**
     * @var array $attachmentType 附件类型
     */
    public static $attachmentType = [
        'loanercardfront' => "主贷人身份证正面",
        'loanercardback' => "主贷人身份证反面",
        'loanerface' => "主贷人正脸照",
        'loaner3rdauth' => "主贷人大数据查询授权书",
        'loanerdrivinglicense' => "主贷人驾驶证",
        'loanermaritalcert' => "主贷人结婚证/离婚证",
        'loanercreditreport' => "主贷人征信报告",
        'loanerkosekidocument' => "主贷人户籍资料",
        'loanerhousedocument' => "主贷人房产资料",
        'loanerincomecert' => "主贷人收入证明",
        'loaneraccountstatement' => "主贷人银行流水",
        'loanerassetcert' => "主贷人资产证明",
        'loanercompanydocument' => "主贷人企业资料",
        'loanercompanyaccountstatment' => "主贷人企业流水",
        'loanerotherassetcert' => "主贷人其他资产",
        'piccdocument' => "人保6单",
        'matecardfront' => "配偶身份证正面",
        'matecardback' => "配偶身份证反面",
        'mateface' => "配偶正脸照",
        'matecreditreport' => "配偶征信报告",
        'mateaccountstatement' => "配偶银行流水",
        'mateassetcert' => "配偶资产证明",
        'guar1cardfron' => "担保人一身份证正面",
        'guar1cardback' => "担保人一身份证反面",
        'guar2cardfront' => "担保人二身份证正面",
        'guar2cardback' => "担保人二身份证反面",
        'estatedoor' => "小区大门或村镇标记牌",
        'doornumber' => "房屋门牌号或全景",
        'customerandvistor' => "客户与家访员合照",
        'vistorandworkcard' => "家访员与家访员工作证合照",
        'livingroom' => "客厅",
        'bedroom' => "卧室",
        'kitchen' => "厨房",
        'washroom' => "卫生间",
        'carexterior' => "车辆外观照",
        'carvin' => "车架号",
        'cartrunk' => "后备箱",
        'cardashboard' => "仪表盘",
        'carnameplate' => "出厂铭牌",
        'carseats' => "内部前后座位",
        'cardrivinglicense' => "行驶证",
        'carregistercert' => "登记证",
        'carandcustomerandvistor' => "车辆、主贷人、家访员合照",
        'carandchecker' => "验车人与车辆合照",
        'carassessreport' => "车辆评估报告",
        'carinvoicepurchase' => "购车发票",
        'carqualitycert' => "新车合格证",
        'carinvoicepurchasetax' => "新车购置税发票",
        'carinvoicecommercialinsure' => "商业险发票",
        'carinvoicetrafficinsure' => "交强险发票",
        'visa' => "签约视频",
        'loancontract' => "贷款合同",
        'mortgagecontract' => "抵押合同",
        'mortgagedregistercert' => "办押后机动车辆登记证书",
        'loanercreditauth' => "主贷人征信授权书",
        'loanerandcardandcreditauth' => "人手持身份证和授权书招聘",
        'policy' => "保单",
        'purposestate' => "用途声明",
        'withholdauth' => "代扣授权书",
        'underwriteconfirmation' => "核保确认书",
        'underwriteletter' => "承保意向书",
        'affiliationagreement' => "挂靠协议",
        'businesslicense' => "营业执照",
        'shareholdermeetresolution' => "股东会议决议",
        'companyassociation' => "公司章程",
        'contractforloanpurpose' => "贷款用途的消费合同",
        'rentcontract' => "租赁合同",
        'carcontractpurchase' => "购车协议",
        'bankcard' => "银行卡",
        'creditrequest' => "贷款申请书",
        'householdregister' => "户口本",
        'withholdapplication' => "他行卡代扣申请书",
        'roadpermit' => "道路经营许可证或类似证明",
        'undertaking' => "贷款承诺书",
        'undertakingvideo' => "承诺书面签视频",
    ];

    /*对接宁波人保 验签-----------begin*/
    private function encryptBody($requestData, $now) {
        $toEncryptData = $requestData;
        $toEncryptData['timestamp'] = $now;
        return $this->encryptRSA(json_encode($toEncryptData));
    }
    private function encryptRSA($sourceData) {
        //Vendor('RSA.RSA','','.php');
        $rsa = new RSA(\Yii::getAlias('@common').'/components/huaxiayinhang/renbao_public.pem', \Yii::getAlias('@common').'/components/huaxiayinhang/private2.pem');
        return $rsa->encrypt($sourceData);
    }

    private function decryptRSA($encryptData) {
//        Vendor('RSA.RSA','','.php');
        $rsa = new RSA(\Yii::getAlias('@common').'/components/huaxiayinhang/public2.pem', \Yii::getAlias('@common').'/components/huaxiayinhang/private2.pem');
        return $rsa->decrypt($encryptData);
    }

    private function sign($requestBody) {
        ksort($requestBody);
        foreach($requestBody as $key => $each) {
            $requestStringArray[] = $key . "=" . $each;
        }
        $requestString = implode('&', $requestStringArray);
        return $this->signRSA($requestString);
    }

    private function signRSA($sourceData) {
        $pubfile = \Yii::getAlias('@common').'/components/huaxiayinhang/public2.pem';
        $prifile =  \Yii::getAlias('@common').'/components/huaxiayinhang/private2.pem';
        $rsa = new RSA($pubfile, $prifile);
        $sourceData = strtoupper(bin2hex(hash('sha256', $sourceData, true)));
        return $rsa->sign($sourceData);
    }

    private function verify($sourceData, $sign) {
        ksort($sourceData);
        foreach($sourceData as $key => $each) {
            $responseStringArray[] = $key . "=" . $each;
        }
        $responseString = implode('&', $responseStringArray);
        return $this->verifyRSA($responseString, $sign);
    }

    private function verifyRSA($sourceData, $sign) {
        $rsa = new RSA(\Yii::getAlias('@common').'/components/huaxiayinhang/renbao_public.pem', \Yii::getAlias('@common').'/components/huaxiayinhang/private2.pem');
        $sourceData = strtoupper(bin2hex(hash('sha256', $sourceData, true)));
        return $rsa->verify($sourceData, $sign);
    }

    private function parseResponse($response) {
        $infoSign = $response['infoSign'];
        unset($response['infoSign']);
        $verifyResult = $this->verify($response, $infoSign);
        if(false == $verifyResult) {
            return array('status' => false, 'message' => '验签失败');
        }
        $responseData = json_decode($this->decryptRSA($response['infoContent']), true);
        return array('status' => true, 'data' => $responseData);
    }
    /*对接宁波人保 验签-----------end*/

    public function decryptInfoContent($infoContent)
    {
        $_info = $this->decryptRSA($infoContent);
        $_info = Tools::unicode2utf8($_info);
        return $_info;
    }
}